package com.searchdemo.lucene;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
	
	public static String doPost(String uri, Map<String, Object> params){
		HttpPost post = new HttpPost(uri);
		setRequestParams(post, params);
		return getDatas(post);
	}

	public static String doGet(String uri){
		return getDatas(new HttpGet(uri));
	}

	public static String doPut(String uri, Map<String, Object> params) {
		HttpPut put = new HttpPut(uri);
		setRequestParams(put, params);
		
		return getDatas(put);
	}
	
	private static void setRequestParams(HttpUriRequest req, Map<String, Object> params){
		if(params!=null){
			for(Map.Entry<String, Object> entry : params.entrySet()){
				req.getParams().setParameter(entry.getKey(), entry.getValue());
			}
		}
	}

	public static String getDatas(HttpUriRequest httpUriRequest) {
		String datas = "";
		HttpClient httpClient = null;
		try {
			httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(httpUriRequest);
			//if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				datas = EntityUtils.toString(entity, "UTF-8");
			//}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		return datas;
	}

}
